import networkx as nx
import matplotlib
matplotlib.use('TkAgg')  # 或者 'Qt5Agg' 等其他后端
import matplotlib.pyplot as plt


def draw_directed_graph(G):
    try:
        # 检查图是否为空
        if not G.nodes or not G.edges:
            print("The graph is empty, nothing to draw.")
            return

        # 设置图形大小
        plt.figure(figsize=(10, 8))

        # 选择布局算法并缓存结果
        pos = nx.spring_layout(G)

        # 绘制节点
        nx.draw_networkx_nodes(G, pos, node_size=500, node_color='skyblue')

        # 绘制边
        nx.draw_networkx_edges(G, pos, edge_color='gray')

        # 绘制节点标签
        nx.draw_networkx_labels(G, pos, font_size=12, font_weight='bold')

        # 添加标题
        plt.title("Simple Directed Network Graph")

        # 隐藏坐标轴
        plt.axis('off')

        # 显示图形（非阻塞方式）
        plt.show(block=False)

    except ImportError as e:
        print(f"Required library not found: {e}")
    except Exception as e:
        print(f"An error occurred while drawing the graph: {e}")

# 创建一个有向图
G = nx.DiGraph()

# 添加节点
G.add_nodes_from([1, 2, 3, 4, 5])

# 添加边
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 5), (5, 1)])

# 调用绘图函数
draw_directed_graph(G)
ss = input("任意键结束")